using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using RollManager.Library.Utils;

namespace RollManager.Library.ActionSteps
{
    [Serializable]
    public class KillRemoteProcessStep : ActionStep
    {
        private string m_processName = StepConstants.NAME;
        private bool m_descendents = true;

        [DisplayName( "Kill Descendents" )]
        [Description( "Whether process and its descendents should be killed." )]
        public bool Descendents
        {
            get
            {
                return m_descendents;
            }
            set
            {
                m_descendents = value;
            }
        }

        [DisplayName( "Process Name" )]
        [Description( "The name of the process to kill on the server." )]
        public string ProcessName
        {
            get
            {
                return m_processName;
            }
            set
            {
                if( string.IsNullOrEmpty( value ) )
                {
                    throw new ArgumentException( "Process Name cannot be empty." );
                }
                else
                {
                    m_processName = value.Trim();
                }
            }
        }

        public override string Name
        {
            get { return "Kill Remote Process"; }
        }

        protected override void Run()
        {
            string command = Path.Combine( Common.PsToolsDir, "pskill.exe" );
            string args = string.Format( @"\\{0} {1}", CurrentServer, m_processName );
            if( m_descendents )
            {
                args = string.Format( @"-t {0}", args );
            }

            MethodRepeater.RepeatMethod( delegate
            {
                Common.RunCommand( command, args, Progress );
            }, Progress, 5 );
        }

        protected override void Simulate()
        {
            // Check for existence of process on server
            Process[] processes = Process.GetProcessesByName( m_processName, CurrentServer );
            if( processes == null || processes.Length == 0 )
            {
                Progress.AddFormat( "WARNING!!!!  Process {0} does not exist on {1}.", m_processName, CurrentServer );
            }
        }
    }
}
